from server import db, api_auth, user_opt
from flask import jsonify, Blueprint, request, g
from server.model.sys.role import Role
from server.model import set_field, query_by_field
import math

r_role = Blueprint('role', __name__)


@r_role.route('', methods=['GET'])
@api_auth.login_required
def get_roles():
    """
                    @@@
                    #### Args:
                           {
                                page: 1,
                                limit: 20,
                                filter: {},
                                start_time: "2021-09-10",
                                end_time: "2021-09-12",
                            }
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in role_list],
                            }
                """
    page = request.args.get('page', type=int, default=1)
    limit = request.args.get('limit', type=int, default=20)
    key_word = request.args.get('key_word')
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    query_filter = request.args.get('filter')

    try:

        role_list = Role.query

        # role_list = query_by_field(g.user, role_list, query_filter, Role)

        if start_time:
            role_list = role_list.filter(db.cast(Role.create_time, db.Date) >= start_time)

        if end_time:
            role_list = role_list.filter(db.cast(Role.create_time, db.Date) <= end_time)
        total = role_list.count()

        role_list = role_list.offset((page - 1) * limit).limit(limit).all()

        return jsonify({
            'code': 20000,
            'message': 'success',
            'items': [u.to_dict() for u in role_list],
            'totalCount': total,
            'TotalPageCount': math.ceil(int(total / limit))
        })
    except Exception as e:
        print("get roles error:", e)

    return jsonify({'code': 50001, 'message': "查询角色时发生错误"})


# >>>>> auto generate end <<<<<

from server.model.sys import PERMISSION
from server.model.sys.role_route import RoleRoute


@r_role.route('', methods=['POST'])
@api_auth.login_required
def add_role():
    """
    @@@
    #### Args:
            {
            }
    #### Returns::
            {'code': 20000, 'message': "角色添加成功"}
            {'code': 50001, 'message': "添加角色时发生错误"}
    """

    args = request.get_json()
    routes = args.get('routes')

    try:
        role = Role()
        set_field(role, args)
        db.session.add(role)
        db.session.flush()

        for key, value in routes.items():
            permission = PERMISSION.li_to_per(value)
            route_route = RoleRoute(role_id=role.id, route_id=key, permission=permission)
            db.session.add(route_route)
        db.session.commit()

        user_opt.send({
            "operation": "添加角色",
            "method": "角色管理",
            "params": role.id,
            "user_id": g.user.id,
            "username": g.user.username
        })

        return jsonify({'code': 20000, 'message': "角色添加成功"})
    except Exception as e:
        db.session.rollback()
        print("add role error:", e)

    return jsonify({'code': 50001, 'message': "添加角色时发生错误"})


@r_role.route('/<int:pid>', methods=['DELETE'])
@api_auth.login_required
def remove_role(pid):
    """
        @@@
        #### Args:
                role/id
        #### Returns::
                {'code': 20000, 'message': "角色删除成功"}
                {'code': 50001, 'message': "删除角色时发生错误"}
        """
    try:
        Role.query.filter_by(id=pid).delete()
        RoleRoute.query.filter(RoleRoute.role_id == pid).delete()
        db.session.commit()

        user_opt.send({
            "operation": "删除角色",
            "method": "角色管理",
            "params": pid,
            "user_id": g.user.id,
            "username": g.user.username
        })
        return jsonify({'code': 20000, 'message': "角色删除成功"})
    except Exception as e:
        print("remove role error:", e)
        return jsonify({
            'code': 50001,
            'message': "删除角色时发生错误"
        })


@r_role.route('/<int:pid>', methods=['PUT'])
@api_auth.login_required
def edit_role(pid):
    """
    @@@
    #### Args:
           role/id
           routes: {{route}...}
    #### Returns::
            {'code': 20000, 'message': "角色修改成功"}
            {'code': 50001, 'message': "修改角色时发生错误"}
    """
    args = request.get_json()
    routes = args.get('routes')
    try:
        role = Role.query.filter_by(id=pid).first()

        RoleRoute.query.filter(RoleRoute.role_id == pid).delete()

        for key, value in routes.items():
            permission = PERMISSION.li_to_per(value)
            route_route = RoleRoute(role_id=pid, route_id=key, permission=permission)
            db.session.add(route_route)

        set_field(role, args)

        db.session.commit()

        user_opt.send({
            "operation": "修改角色",
            "method": "角色管理",
            "params": pid,
            "user_id": g.user.id,
            "username": g.user.username
        })
        return jsonify({'code': 20000, 'message': "角色修改成功"})
    except Exception as e:
        db.session.rollback()
        print("edit role error:", e)

    return jsonify({'code': 50001, 'message': "修改角色时发生错误"})


@r_role.route('/<int:pid>', methods=['GET'])
@api_auth.login_required
def get_detail(pid):
    """
                    @@@
                    #### Args:
                           role/id
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in role_list],
                            }
                """
    role = Role.query.filter_by(id=pid).first()
    if not role:
        return jsonify({
            'code': 50002,
            'message': '查询角色不存在'
        })
    role_routes = role.get_role_routes()
    result = role.to_dict()
    result['routes'] = [u.to_dict() for u in role_routes]

    return jsonify({
        'code': 20000,
        'message': 'success',
        'items': result,
    })
